<?php
namespace process;

use Workerman\Crontab\Crontab;
use think\facade\Db;
use support\Log;
use support\Container;


class Task
{
	
    public function onWorkerStart()
    {
		$list = Db::name('crontab')->where('status',1)->select();
		foreach($list as $v){
			switch($v['type']){
				case 1:
					new Crontab($v['rule'], function() use ($v){
						$client    = new \GuzzleHttp\Client();
						try {
							$response = $client->get(trim($v['target']));
							$result   = $response->getStatusCode() === 200;
						} catch (\Throwable $throwable) {
							$result    = false;
						}
						$this->logResult($v['name'], $result);
						Db::name('crontab')->where('crontab_id',$v['crontab_id'])->update(['last_run_time'=>time()]);
					});
				break;
				
				case 2:
					new Crontab($v['rule'], function() use ($v){
						$class = 'task\\'.$v['target'];
						$method = 'execute';
						if ($class && class_exists($class) && method_exists($class, $method)) {
							try {
								$result   = true;
								$res = Container::get($class)->{$method}();
							} catch (\Throwable $throwable) {
								$result = false;
							}
						} else {
							$result    = false;
						}
						$this->logResult($v['name'], $result);
						Db::name('crontab')->where('crontab_id',$v['crontab_id'])->update(['last_run_time'=>time()]);
					});
				break;
			}
		}
    }
	
	
	protected function logResult($name, $isSuccess)
    {
		if ($isSuccess) {
			Log::info(sprintf('Crontab task [%s] executed successfully at %s.', $name, date('Y-m-d H:i:s')));
		} else {
			Log::error(sprintf('Crontab task [%s] failed execution at %s.', $name, date('Y-m-d H:i:s')));
		}
    }
	
}